package com.yigerende.aspect;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/*
*日志处理
*  */
@Aspect/*进行aop切面操作*/
@Component//注解扫描
public class LogAspect {

    /*日志logger*/
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //规定这个切面拦截的是那些包里面的类(所有拦截控制器的类)（只要程序进过这些控制器都会执行这个切面类）
    @Pointcut("execution(* com.yigerende.web.*.*(..))")
    public void log() {}


    //切面之前的方法
    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        /*上面就拿到了request参数*/

        /*下面开始取request里面的东西*/
        String url = request.getRequestURL().toString();//url
        String ip = request.getRemoteAddr();//ip地址
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();//拦截方法名字
        Object[] args = joinPoint.getArgs();

        /*存储到RequestLog这个对象模型*/
        RequestLog requestLog = new RequestLog(url, ip, classMethod, args);
        /*再把这个对象模型传递到日志里面*/
        logger.info("Request : {}", requestLog);
    }


    //切面之后执行的方法
    @After("log()")
    public void doAfter() {
//        logger.info("--------doAfter--------");
    }



    //记录返回的时候的方法（返回的是result，切面是log()）
    @AfterReturning(returning = "result",pointcut = "log()")
    public void doAfterRuturn(Object result) {
        logger.info("Result : {}", result);
    }




    //用对象一次性把需要的属性都接收到了
    private class RequestLog {
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }

}
